#include<stdio.h>
#include <unistd.h>
#include <string.h>

/* liteOS 库 */
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "wifiiot_errno.h"
#include "wifiiot_uart.h"

/* hi 库 */
#include "hi_gpio.h"
#include "hi_wifi_api.h"
#include "lwip/netifapi.h"
#include "hi_types.h"
#include "hi_timer.h"

/* 自定义库 */
#include "bsp_usart.h"

/* 
   demo1_1
   使用串口1接收串口指令控制绿灯的亮灭
*/

static void mymain(void);


/* 串口1收发buf */
uint8_t sendBuf[UART_BUFF_SIZE]={0};
uint8_t *sendBuf_ptr = sendBuf;

uint8_t recvBuf[UART_BUFF_SIZE]={0};
uint8_t *recvBuf_ptr = recvBuf;


/* 串口1 任务 */
static void UART_Task(void)
{

    uint32_t ret;
    uint32_t command;


    /* 串口设置 */
    WifiIotUartAttribute uart_attr = 
    {
        .baudRate = 115200,
        .dataBits = 8,
        .stopBits = 1,
        .parity = 0,
    };

    /* 初始化串口 */
    ret = UartInit(WIFI_IOT_UART_IDX_1, &uart_attr, NULL);
    if (ret != WIFI_IOT_SUCCESS)
    {
        printf("Failed to init uart! Err code = %d\n", ret);
        return;
    }

    printf("UART Test Start\n");
    while (1)
    {
        /* 通过串口1接收数据 */
        UartRead(WIFI_IOT_UART_IDX_1, recvBuf_ptr, UART_BUFF_SIZE);

        //usleep(5000);
        /* 串口指令控制LED灯亮灭 */
        command = recvBuf[1];
	    command = (command <<8)  +  recvBuf[2];
        
        switch(command)
        {
            case LEDON:
                GreenLedOn();
                sendBuf[0] = 0x11;
                Usart_SendArray(sendBuf,10);
                break;
            
            case LEDOFF:
                GreenLedOff();
                break;

            default:
                break;

        }        
    }
}


/* 创建串口工作任务 */
static void UART_ExampleEntry(void)
{

    osThreadAttr_t attr;
    attr.name = "UART_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = UART_TASK_STACK_SIZE;
    attr.priority = UART_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)UART_Task, NULL, &attr) == NULL)
    {
        printf("[ADCExample] Falied to create UART_Task!\n");
    }
}


/* WIFI setup */ 
int hi_wifi_start_connect(void)
{

    int ret;
    errno_t rc;
    hi_wifi_assoc_request assoc_req = {0};

    /* copy SSID to assoc_req */
    rc = memcpy_s(assoc_req.ssid, HI_WIFI_MAX_SSID_LEN + 1, "653", 3); /* 9:ssid length */
    if (rc != EOK) {
        return -1;
    }

    //热点加密方式
    assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;

    /* 热点密码 */
    memcpy(assoc_req.key, "123456789", 9);

    ret = hi_wifi_sta_connect(&assoc_req);
    if (ret != HISI_OK) {
        return -1;
    }

    return 0;
}



/* 主函数 */
static void mymain(void)
{

    printf("=======================================\r\n");
    printf("*************UART_CONTROL_LED**********\r\n");
    printf("=======================================\r\n");


    LED_INIT();
    GreenLedOn();
    UART_ExampleEntry();
    hi_wifi_start_connect();
}


APP_FEATURE_INIT(mymain);
